package com.zx.flow.api.util;

import com.alibaba.fastjson2.JSONObject;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;

public class GroovyScriptUtil {

    private static GroovyScriptEngineFactory scriptEngineFactory = new GroovyScriptEngineFactory();

    private static Map<String, ScriptEngine> scriptEngineCache = new ConcurrentHashMap<>();

    public static Boolean conditionAction(String conditionScript, String data) throws Exception {
        JSONObject dataJson = Util.getJsonObject(data);
        String script = "def condition(Map data) { " +
                "       return  " + conditionScript + ";" +
                "}";
        Boolean res = invoke(script, "condition", dataJson);
        return res;
    }

    /**
     * 使用ScriptEngine
     *
     * @param script
     * @param function
     * @param objects
     * @param <T>
     * @return
     * @throws Exception
     */
    private static <T> T invoke(String script, String function, Object... objects) throws Exception {
        ScriptEngine scriptEngine = null;
        if (scriptEngineCache.containsKey(script)) {
            scriptEngine = scriptEngineCache.get(script);
        } else {
            scriptEngine = scriptEngineFactory.getScriptEngine();
            scriptEngine.eval(script);
            scriptEngineCache.put(script, scriptEngine);
        }
        return (T) ((Invocable) scriptEngine).invokeFunction(function, objects);
    }

}
